//
//  RemotePlayerDownloader.m
//  MenkRemotePlayer
//
//  Created by Burn on 2019/7/4.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "RemotePlayerDownloader.h"
#import "RemotePlayerFileManager.h"
@interface RemotePlayerDownloader ()<NSURLSessionDataDelegate>

@property(strong,nonatomic) NSOutputStream *outputStream;
@property(strong,nonatomic) NSURLSession *session;

@end

@implementation RemotePlayerDownloader

- (NSURLSession *)session{
    if (!_session) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}


- (void)downloadWithURL:(NSURL *)url offset:(NSInteger)offset{
    [self cancelAndClean];
    [[RemotePlayerFileManager shared]clearTempWith:url];
    self.offset = offset;
    self.url = url;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:0];
    [request setValue:[NSString stringWithFormat:@"bytes=%ld-", (long)offset] forHTTPHeaderField:@"Range"];
    NSURLSessionTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
}

- (void)cancelAndClean{
    @synchronized (self) {
        _totalSize = 0;
    }
    [self.session invalidateAndCancel];
    self.session = nil;
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}

#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{
    // !!!: 接收到响应
    
    //  获取totalSize
    NSInteger contentLenght = [response.allHeaderFields[@"Content-Length"] integerValue];
    if (contentLenght) {
        self.totalSize = contentLenght;
    }
    
    NSString *contentRangeString = response.allHeaderFields[@"Content-Length"];
    if (contentRangeString.length > 0) {
        NSString *totalSizeString = [[contentRangeString componentsSeparatedByString:@"/"] lastObject];
        self.totalSize = [totalSizeString integerValue];
    }
    
    
    //  MIMEType
    if (response.MIMEType.length > 0) {
        self.MIMEType = response.MIMEType;
    }else{
        self.MIMEType = @"video/mp4";
    }
    
    //  接受响应的时候-准备好输入流
    self.outputStream = [NSOutputStream outputStreamToFileAtPath:[[RemotePlayerFileManager shared]tempFilePathWith:self.url] append:YES];
    [self.outputStream open];
    completionHandler(NSURLSessionResponseAllow);
    NSLog(@"%@",[[RemotePlayerFileManager shared]tempFilePathWith:self.url]);

}


- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    // !!!: 接收到数据
    
    //  写入数据
    [self.outputStream write:[data bytes] maxLength:data.length];
    self.loadSize += data.length;
    
    //  调用代理
    if ([self.delegate  respondsToSelector:@selector(downLoading)]) {
        [self.delegate downLoading];
    }
}


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    // !!!: 结束
    
    if (error == nil) {
        NSInteger tempSize = [[RemotePlayerFileManager shared] tempFileSizeWith:self.url];
        if (self.totalSize == tempSize) {
            [[RemotePlayerFileManager shared]moveFileWith:self.url];
        }else{
            if ([self.delegate respondsToSelector:@selector(taskError_999:offset:)]) {
                [self.delegate taskError_999:self.url offset:self.offset];
            }
        }
        
    }else if (error.code == -1002){
        [[NSNotificationCenter defaultCenter]postNotificationName:URLNAGETIVE1002 object:nil];
    }

}


-(void)dealloc{
    
}

@end
